package edu.hawaii.duedates;

import java.util.TimerTask;

/**
 * Wakeup class that executes the scheduled task.
 * 
 * @author John Zhou
 * @author John Ly
 */
public class Wakeup extends TimerTask {
  private final String [] args;
  private String toAddr = "";
  private String smtpServer = "";
  private boolean sendEmail = false;
  private boolean console = false;
  
  /**
   * Constructor for Wakeup.
   * @param args The arguments inputted into the system.
   */
  public Wakeup(String[] args) {
    this.args = args.clone();
  }

  /**
   * Runs the scheduled task.
   */
  @Override
  public void run() {
    System.out.println("Executing scheduled task:");
    DueDates dueDatesTask = new DueDates (args);
    try {
      for (int i = 0; i < args.length; i++) {
        if (args[i].equals("-email")) {
          sendEmail = true;
          toAddr = args[i + 1];
          smtpServer = args[i + 2];
          i = i + 2;
        }
        else if (args[i].equals("-console")) {
          console = true;
        }
      }
      if (sendEmail) {
        dueDatesTask.sendEmail(dueDatesTask.getItemList(), toAddr, smtpServer);
      }
      if (console) {
        System.out.printf(dueDatesTask.printResults(dueDatesTask.getItemList()));
      }
    }
    catch (ArrayIndexOutOfBoundsException ae) {
      System.out.println("Invalid number of arguments");
    }
    catch (Exception e) {
      System.out.println("Error: " + e.getMessage());
      dueDatesTask.printResults(dueDatesTask.getItemList());
    }
  }
}
